//产品视图
var exports = {};

var panel = $(".chooseDesign");

var _galleryCategoryDatas = null;
var _typeValue = "2";
var _topClassValue = "";
var _twoClassValue = "";

var _viewType = "img";
var _currPageIndex = 1; //当前页
var _pageMax = 10; //总页数
var _ids = [];

var _searchKey = "";


exports.init = function() {
	initView();
	
	$(".chooseDesign").find(".searchBtn").on("click", doSearchBtn);
	function doSearchBtn(){
		var key = $(".chooseDesign .searchText").val();
		_searchKey = $.trim(key);
		renderImgList();
	}
}

function getGalleryCategoryDatas(callBack) {
	var url = config_gl.apiPath + "galleryCategory/list";
	$.ajax(url, {
		type: 'post', //HTTP请求类型
		contentType: "application/json",
		data: JSON.stringify({
			"limit": 1000,
			"page": 1
		}),
		success: function(data) {
			callBack(data);
		},
		error: function(xhr, type, errorThrown) {
			layer.alert("获取图库分类未知错误");
		}
	});
}

function initView() {
	layui.form.on('select(imgTypeClass)', function(data) {
		_typeValue = data.value;
		_topClassValue = "";
		_twoClassValue = "";
		updateTopClassView();
	});

	getGalleryCategoryDatas(function(data) {
		_galleryCategoryDatas = data.data;
		updateTopClassView();
	});

	//颜色拾取器
	$('#chooseBackgroundSelf-picker').colpick({
		flat: true,
		layout: 'hex',
		submit: 0,
		onChange: function(v) {
			var color = $("#chooseBackgroundSelf-picker").find(".colpick_hex_field").find("input").val();
			updateColor("#" + color);
		}
	});

	$(".chooseBackgroundSelf-ul").find("li").on("click", function() {
		var color = $(this).data("fontcolor");
		updateColor(color);
	})

	function updateColor(color) {
		var rect = Design.mainEditer.getEditeRect();
		if (rect) {
			var bgele = Design.mainEditer.currFace().bg;
			if (bgele) {
				bgele.bgColor = color;
				bgele.update();
			} else {
				var realScale = Design.mainEditer.product.realScale || 1;
				var scale = 1 / realScale;
				var data = {
					type: "bg",
					bgColor: color,
					x: rect.x,
					y: rect.y,
					scalex: scale,
					scaley: scale,
				}
				Design.event.trigger(Design.event.ADD_ELEMENT, data);
			}
		}
	}

	/* 切换成图库 */
	$(".chooseBackgroundGallery").on("click", function() {
		$(".chooseBackgroundSelf").removeClass("cur");
		$(this).addClass("cur");
		$(".gallery-div").show();
		$(".chooseBackgroundSelf-div").hide();
	})

	/* 切换成背景色 */
	$(".chooseBackgroundSelf").on("click", function() {
		$(".chooseBackgroundGallery").removeClass("cur");
		$(this).addClass("cur");
		$(".gallery-div").hide();
		$(".chooseBackgroundSelf-div").show();
	})
}

function updateTopClassView() {
	var uldom = panel.find(".category-top");
	uldom.empty();
	var list = _galleryCategoryDatas;
	uldom.append('<option value="">全部</option>');
	for (var i = 0; i < list.length; i++) {
		var d = list[i];
		uldom.append('<option value="' + d.id + '">' + d.name + '</option>');
	}

	if (list.length <= 1) {
		$("#categoryTop").hide();
	} else {
		$("#categoryTop").show();
	}

	layui.form.on('select(imgTopClass)', function(data) {
		_topClassValue = data.value;
		_twoClassValue = "";
		updateTwoClassView();
	});

	layui.form.render('select');
	updateTwoClassView();
}

function updateTwoClassView() {
	var uldom = panel.find(".category-two");
	uldom.empty();
	var list = [];
	for (var i = 0; i < _galleryCategoryDatas.length; i++) {
		var d = _galleryCategoryDatas[i];
		if (_topClassValue == "") {
			list = list.concat(d.secondLevel);
		} else if (_topClassValue == d.id) {
			list = list.concat(d.secondLevel);
		}
	}
	uldom.append('<option value="">全部</option>');
	for (var i = 0; i < list.length; i++) {
		var d = list[i];
		uldom.append('<option value="' + d.id + '">' + d.name + '</option>');
	}

	if (list.length <= 1) {
		$("#categoryTwo").hide();
	} else {
		$("#categoryTwo").show();
	}

	layui.form.on('select(imgTwoClass)', function(data) {
		_twoClassValue = data.value;
		renderImgList();
	});
	layui.form.render('select');

	renderImgList();
}

function renderImgList() {
	var ids = "";
	if (_twoClassValue != "") {
		ids = _twoClassValue;
	} else if (_topClassValue != "") {
		ids = _topClassValue;
	}
	panel.find(".curPage").text(_currPageIndex);
	var fdata = {
		"limit": 20,
		"page": _currPageIndex,
		"type": _typeValue,
		"ids": ids,
		"searchKey": _searchKey
	}
	var url = config_gl.apiPath + "gallery/list";
	$.ajax(url, {
		type: 'post', //HTTP请求类型
		contentType: "application/json",
		data: JSON.stringify(fdata),
		success: function(data) {
			var list = data.data;
			var ul = $("#gallery");
			ul.empty();
			for (var i = 0; i < list.length; i++) {
				var d = list[i];
				var li = '<div class="galleryImg" data-name="' + d.name + '" data-w="' + d.width + '" data-h="' + d.height +
					'" data-path="' + d.path + '"><img src="' + d.path + '" ></div>';
				ul.append(li);
			}
			ul.find(".galleryImg").off("click").on("click", addImagToStage);
			_pageMax = Math.ceil(data.count / fdata.limit);
			panel.find(".totalPage").text(_pageMax);
		},
		error: function(xhr, type, errorThrown) {
			layer.alert("获取图片未知错误");
		}
	});
}

/* 将图片添加到舞台 */
function addImagToStage() {
	var url = $(this).data("path");
	var name = $(this).data("name");
	var rect = Design.mainEditer.getEditeRect();
	if (rect) {
		var width = $(this).data("w");
		var height = $(this).data("h");
		var tx = rect.x + rect.width / 2 - width / 2;
		var ty = rect.y + rect.height / 2 - height / 2;

		if (config_gl.apiPath.indexOf("http://127.0.0.1:8086/api") != -1) {
			url = url.replace("47.106.65.176", "127.0.0.1:8086");
		}

		var realScale = Design.mainEditer.product.realScale || 1;
		var scale = 1 / realScale;
		if(width*scale > rect.width){
			scale = rect.width / width;
			tx = rect.x;
			ty = rect.y;
		}
		if (_viewType == "img") {
			var data = {
				type: "img",
				url: url,
				x: tx,
				y: ty,
				scalex: scale,
				scaley: scale,
				name: name
			}
			Design.event.trigger(Design.event.ADD_ELEMENT, data);
		} else {
			var data = {
				type: "bg",
				url: url,
				x: tx,
				y: ty,
				scalex: scale,
				scaley: scale,
				name: name
			}
			Design.event.trigger(Design.event.ADD_ELEMENT, data);
		}
	}
}

exports.updateView = function(type) {
	_viewType = type;
	if (type == "img") {
		$(".chooseDesign .chooseBackgroundSelf").hide();
		$(".chooseBackgroundGallery").trigger("click");
	} else {
		$(".chooseDesign .chooseBackgroundSelf").show();
	}
}

panel.find(".prePage").on("click", doPrePage);
panel.find(".nextPage").on("click", doNextPage);
panel.find(".choosePageGo").on("click", pageGoHandler);

/* 上一页 */
function doPrePage() {
	if (_currPageIndex > 1) {
		_currPageIndex--;
		renderImgList();
	}
}

/* 下一页 */
function doNextPage() {
	if (_currPageIndex < _pageMax) {
		_currPageIndex++;
		renderImgList();
	}
}

/* 页面跳转 */
function pageGoHandler() {
	var goIndex = panel.find(".choosePage").val();
	goIndex = parseInt(goIndex);
	if (goIndex > 0 && goIndex <= _pageMax) {
		if (!isNaN(goIndex) && goIndex != _currPageIndex) {
			_currPageIndex = goIndex;
			renderImgList();
		}
	} else {
		panel.find(".choosePage").text("");
	}
}

module.exports = exports;
